<?php

namespace App\Service\User;

use Illuminate\Support\Facades\Redis;
use Carbon\Carbon;

class UserService
{
    /**
     * 检查用户今天是否已签到
     *
     * @param int $userId
     * @return bool
     */
    public static function isCheckIn($userId)
    {
        $today = Carbon::today()->format('Y-m-d');
        $key = "user:checkin:{$userId}:{$today}";
        
        return Redis::exists($key);
    }

    /**
     * 用户签到
     *
     * @param int $userId
     * @return array
     */
    public static function checkIn($userId)
    {
        $today = Carbon::today()->format('Y-m-d');
        $key = "user:checkin:{$userId}:{$today}";
        
        // 检查是否已签到
        if (Redis::exists($key)) {
            return [
                'success' => false,
                'message' => '今天已经签到过了',
                'data' => [
                    'checkin_time' => Redis::get($key),
                    'is_checkin' => true
                ]
            ];
        }
        
        // 执行签到
        $checkinTime = Carbon::now()->format('Y-m-d H:i:s');
        Redis::setex($key, 86400, $checkinTime); // 24小时过期
        
        // 更新连续签到天数
        $streakKey = "user:checkin:streak:{$userId}";
        $yesterday = Carbon::yesterday()->format('Y-m-d');
        $yesterdayKey = "user:checkin:{$userId}:{$yesterday}";
        
        if (Redis::exists($yesterdayKey)) {
            // 昨天有签到，连续天数+1
            Redis::incr($streakKey);
        } else {
            // 昨天没有签到，重置为1
            Redis::set($streakKey, 1);
        }
        
        $streakDays = Redis::get($streakKey) ?: 1;
        
        return [
            'success' => true,
            'message' => '签到成功',
            'data' => [
                'checkin_time' => $checkinTime,
                'streak_days' => (int)$streakDays,
                'is_checkin' => true
            ]
        ];
    }

    /**
     * 获取用户签到信息
     *
     * @param int $userId
     * @return array
     */
    public static function getCheckInInfo($userId)
    {
        $today = Carbon::today()->format('Y-m-d');
        $key = "user:checkin:{$userId}:{$today}";
        $streakKey = "user:checkin:streak:{$userId}";
        
        $isCheckin = Redis::exists($key);
        $checkinTime = $isCheckin ? Redis::get($key) : null;
        $streakDays = Redis::get($streakKey) ?: 0;
        
        return [
            'is_checkin' => $isCheckin,
            'checkin_time' => $checkinTime,
            'streak_days' => (int)$streakDays
        ];
    }
}